﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using SMARTMobile.Common;
using SmartMobile.Data;
using SMARTMobile.Services.SMARTMobileServiceReference;
using SMARTMobile.WinPhone;

namespace SMARTMobile.ViewModels
{
    public class DongBoPageViewModel : ViewModelBase
    {
        private SmartMobileDBContext _smartMobileContext;
        private ReloadDataSmartPhoneSoapClient _proxy;
        List<TCARCUST> updateTcarcusts = new List<TCARCUST>();
        private int countUpdate = 0;
        private int countUpdateComplete = 0;
        private bool _isCheckedInformation;
        private int _indexUpload = -1;
        private int _indexUploadImage = 0;
        private List<PhonevendorVolume> _uploadPhonevendorVolumeList = new List<PhonevendorVolume>();
        private List<PriceRangeContribution> _uploadPriceRangeContributionList = new List<PriceRangeContribution>();
        private List<OutetPGInformation> _uploadOutetPGInformationList = new List<OutetPGInformation>();
        private List<OutletVendorContribution> _uploadOutletVendorContributionList = new List<OutletVendorContribution>();
        public DongBoPageViewModel()
        {
            Microsoft.Phone.Shell.PhoneApplicationService.Current.UserIdleDetectionMode = Microsoft.Phone.Shell.IdleDetectionMode.Disabled;

            this.ThoatCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteThoatCommand
            };

            this.SaveCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteSaveCommand
            };

            this._smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            this._proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);
            this._proxy.InsertCustomerkeyCompleted += _proxy_InsertCustomerkeyCompleted;
            this._proxy.UploadCustomerImageCompleted += _proxy_UploadCustomerImageCompleted;
            this._proxy.UploadPhonevendorVolumeCompleted += _proxy_UploadPhonevendorVolumeCompleted;
            this._proxy.UploadPriceRangeContributionCompleted += _proxy_UploadPriceRangeContributionCompleted;
            this._proxy.UploadOutletPGInformationCompleted += _proxy_UploadOutletPGInformationCompleted;
            this._proxy.UploadOutletNokiaMerchandisingPotentialCompleted += _proxy_UploadOutletNokiaMerchandisingPotentialCompleted;
            this._proxy.UploadShopvisitCompleted += this._proxy_UploadShopvisitCompleted;
            this._proxy.ApprovalCustomerInforCompleted += _proxy_ApprovalCustomerInforCompleted;
            this._proxy.UploadCurrentInDoorDoorDisplayCompleted += _proxy_UploadCurrentInDoorDoorDisplayCompleted;
            this._proxy.UploadCurrentOutDoorDisplayCompleted += _proxy_UploadCurrentOutDoorDisplayCompleted;
            ////this._proxy.UploadContactInforCompleted += _proxy_UploadContactInforCompleted;
            this._proxy.UploadOutltVendorContributionCompleted += _proxy_UploadOutltVendorContributionCompleted;

            if (GlobalInformation.ReportImageTypes == null || !GlobalInformation.ReportImageTypes.Any())
            {
                GlobalInformation.ReportImageTypes = GetImageType();
            }
        }

        public ICommandRoute ThoatCommand { get; private set; }

        public ICommandRoute SaveCommand { get; private set; }

        public bool IsCheckedInformation
        {
            get { return _isCheckedInformation; }
            set
            {
                _isCheckedInformation = value;
                base.RaisePropertyChanged("IsCheckedInformation");
            }
        }

        private void ExecuteSaveCommand(object commandParams)
        {
            if (!GlobalInformation.CheckNetworkStatus())
            {
                this.SaveCommand.RaiseCanExecuteChanged(true);
                ////this.ShowMessage("Không thể kết nối Internet");
                return;
            }

            this.IsBusy = true;
            Deployment.Current.Dispatcher.BeginInvoke(() => this.SaveCommand.RaiseCanExecuteChanged(false));
            countUpdate = 0;
            updateTcarcusts.Clear();
            _uploadPhonevendorVolumeList.Clear();
            _uploadPriceRangeContributionList.Clear();
            _uploadOutetPGInformationList.Clear();
            _uploadOutletVendorContributionList.Clear();

            GetListToUpdate();
            if (this.IsCheckedInformation)
            {
                // new method
                this.NewSaveCommand();
                return;
            }
            else
            {
                this.IsBusy = false;
                this.SaveCommand.RaiseCanExecuteChanged(true);
            }
        }

        private void GetListToUpdate()
        {
            foreach (var shopVisit in this._smartMobileContext.Shopvisit)
            {
                var phoneVendors = this._smartMobileContext.PhonevendorVolume.Where(a => a.CustomerKey == shopVisit.CustomerKey);
                if (phoneVendors != null)
                {
                    _uploadPhonevendorVolumeList.AddRange(phoneVendors);
                }

                var priceContributions = this._smartMobileContext.PriceRangeContribution.Where(a => a.CustomerKey == shopVisit.CustomerKey);
                if (priceContributions != null)
                {
                    _uploadPriceRangeContributionList.AddRange(priceContributions);
                }

                var pgInformations = this._smartMobileContext.OutetPGInformation.Where(a => a.Customerkey == shopVisit.CustomerKey); ;
                if (pgInformations != null)
                {
                    _uploadOutetPGInformationList.AddRange(pgInformations);
                }

                var outletVendorContributions = this._smartMobileContext.OutletVendorContribution.Where(a => a.CustomerKey == shopVisit.CustomerKey); ;
                if (outletVendorContributions != null)
                {
                    _uploadOutletVendorContributionList.AddRange(outletVendorContributions);
                }
            }
        }

        private void ExecuteThoatCommand(object commandParams)
        {
            this.ThoatCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("Main");
        }

        private List<IMAGETYPE> GetImageType()
        {
            try
            {
                // It will copy from local to iso
                _smartMobileContext.CreateIfNotExists();

                // log sql query native on Output window
                _smartMobileContext.LogDebug = true;

                // Query - Same with SQL SERVER Linq
                List<IMAGETYPE> list = new List<IMAGETYPE>();
                return _smartMobileContext.IMAGETYPE.ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        void _proxy_InsertCustomerkeyCompleted(object sender, InsertCustomerkeyCompletedEventArgs e)
        {
            try
            {
                //this.BusyText = "Đồng bộ khách hàng";
                countUpdate++;
                // New Customer
                if (e.Result != "0")
                {
                    ////if (!string.IsNullOrEmpty(e.UserState.ToString()))
                    ////{
                    // Update customer key on local database
                    if (GlobalInformation.SelectedTCARCUS != null)
                    {
                        GlobalInformation.SelectedTCARCUS.Customerkey = e.Result;
                    }

                    // Update TCARCUST
                    var currentTCARCUST = (from tcr in _smartMobileContext.TCARCUST where tcr.Customerkey == e.Result select tcr).FirstOrDefault();
                    if (currentTCARCUST != null)
                    {
                        currentTCARCUST.Customerkey = e.Result;
                        currentTCARCUST.IsEdit = "3";
                    }

                    var currentShopVisit = (from shop in _smartMobileContext.Shopvisit where shop.CustomerKey == e.Result select shop).FirstOrDefault();
                    if (currentShopVisit != null)
                    {
                        currentShopVisit.CustomerKey = e.Result;
                    }

                    var currentIMAGECUSTOMER = (from shop in _smartMobileContext.IMAGECUSTOMER where shop.CustomerKey == e.Result select shop).ToList();

                    foreach (var imagecustomer in currentIMAGECUSTOMER)
                    {
                        imagecustomer.CustomerKey = e.Result;
                    }

                    _smartMobileContext.SubmitChanges();
                    ////}

                    this._indexUpload++;
                    this.UpdateCustomers();
                }
                else
                {
                    this._indexUpload++;
                    this.UpdateCustomers();
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(string.Format("Lỗi khi đồng bộ {0}\r\n{1}", "khách hàng", ex.GetBaseException().ToString()));
            }
        }

        private void _proxy_UploadCustomerImageCompleted(object sender, UploadCustomerImageCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                this._indexUpload++;
                this.UpdateImages();
            }
        }

        private void _proxy_UploadPhonevendorVolumeCompleted(object sender, UploadPhonevendorVolumeCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                _indexUpload++;
                UploadPhoneVendor();
            }
            else
            {
                ShowErrorMessage("Lỗi khi đồng bộ doanh số theo hãng: " + Environment.NewLine + e.Error);
            }
        }

        void _proxy_UploadPriceRangeContributionCompleted(object sender, UploadPriceRangeContributionCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                _indexUpload++;
                UploadPriceRange();
            }
            else
            {
                ShowErrorMessage("Lỗi khi đồng bộ tỷ trọng doanh số máy theo khoảng giá: " + Environment.NewLine + e.Error);
            }
        }

        void _proxy_UploadOutletPGInformationCompleted(object sender, UploadOutletPGInformationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                _indexUpload++;
                UploadOuletPGInformation();
            }
            else
            {
                ShowErrorMessage("Lỗi khi đồng bộ Số lượng PG Theo Hãng: " + Environment.NewLine + e.Error);
            }
        }

        void _proxy_UploadOutletNokiaMerchandisingPotentialCompleted(object sender, UploadOutletNokiaMerchandisingPotentialCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                this.UploadOutletNokiaMerchandisingPotential();
            }
            else
            {
                ShowErrorMessage("Lỗi khi đồng bộ Khả năng trưng bày cho Nokia: " + Environment.NewLine + e.Error);
            }
        }

        void _proxy_UploadOutltVendorContributionCompleted(object sender, UploadOutltVendorContributionCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                _indexUpload++;
                UploadOutletVendorContribution();
            }
            else
            {
                ShowErrorMessage("Lỗi khi đồng bộ Tỷ lệ nhập hàng theo NPP: " + Environment.NewLine + e.Error);
            }
        }

        private void UploadPhoneVendor()
        {
            if (_indexUpload < _uploadPhonevendorVolumeList.Count())
            {
                var phoneVendor = _uploadPhonevendorVolumeList[_indexUpload];
                this._proxy.UploadPhonevendorVolumeAsync(GlobalInformation.SiteCode,
                            phoneVendor.CustomerKey, phoneVendor.PhoneVendorCode,
                            (phoneVendor.WhosesaleVolume ?? 0).ToString(), (phoneVendor.RetailVolume ?? 0).ToString(),
                            (phoneVendor.WhosesaleValue ?? 0).ToString(), (phoneVendor.RetailValue ?? 0).ToString());
            }
            else
            {
                _indexUpload = 0;
                UploadPriceRange();
            }
        }

        private void UploadPriceRange()
        {
            if (_indexUpload < _uploadPriceRangeContributionList.Count())
            {
                var priceRange = _uploadPriceRangeContributionList[_indexUpload];
                this._proxy.UploadPriceRangeContributionAsync(GlobalInformation.SiteCode,
                 priceRange.CustomerKey, priceRange.PriceRangeCode
                 , (priceRange.ContributionByValue ?? 0).ToString(),
                 (priceRange.ContributionByVolume).ToString());
            }
            else
            {
                _indexUpload = 0;
                UploadOuletPGInformation();
            }
        }

        //private void UploadOutletNokiaPG()
        //{
        //    if (_indexUpload < this._smartMobileContext.OutletNokiaPG.Count())
        //    {
        //        var nokiaPG = this._smartMobileContext.OutletNokiaPG.ToList()[_indexUpload];
        //        this._proxy.UploadOutletNokiaPGAsync(GlobalInformation.SiteCode,
        //            nokiaPG.Customerkey, nokiaPG.PGCode, nokiaPG.StartWorkingTime.ToString(),
        //            nokiaPG.EndWorkingTime.ToString());
        //    }
        //    else
        //    {
        //        _indexUpload = 0;
        //        UploadOuletPGInformation();
        //    }
        //}

        private void UploadOuletPGInformation()
        {
            if (_indexUpload < _uploadOutetPGInformationList.Count())
            {
                var pgInformation = _uploadOutetPGInformationList[_indexUpload];
                this._proxy.UploadOutletPGInformationAsync(GlobalInformation.SiteCode,
                                pgInformation.Customerkey, pgInformation.PhoneVendorCode,
                                (pgInformation.Qty ?? 0).ToString());
            }
            else
            {
                _indexUpload = 0;
                UploadOutletVendorContribution();
            }
        }

        private void UploadOutletVendorContribution()
        {
            if (_indexUpload < _uploadOutletVendorContributionList.Count())
            {
                var outletVendorContribution = _uploadOutletVendorContributionList[_indexUpload];
                this._proxy.UploadOutltVendorContributionAsync(GlobalInformation.SiteCode,
                    outletVendorContribution.CustomerKey, outletVendorContribution.OutletVendorKey,
                    (outletVendorContribution.ContributionAmt ?? 0).ToString());
            }
            else
            {
                _indexUpload = 0;
                this.UpdateCurrentIn();
            }
        }

        private void UploadOutletNokiaMerchandisingPotential()
        {
            var merchandisings = this._smartMobileContext.OutletNokiaMerchandisingPotential.Where(c => c.Qty != null && c.Qty.Value > 0).OrderBy(c => c.Qty).ToList();

            if (this._indexUpload < 0 || this._indexUpload >= merchandisings.Count)
            {
                this._indexUpload = 0;
                _indexUploadImage = 0;

                // Finish
                this.IsBusy = false;
                this.ShowMessage("Đồng bộ dữ liệu thành công");
                this.ThoatCommand.RaiseCanExecuteChanged(true);
                this.SaveCommand.RaiseCanExecuteChanged(true);
                return;
            }

            OutletNokiaMerchandisingPotential merchandising = merchandisings[_indexUpload];
            if (_indexUploadImage >= merchandising.QtyPicture)
            {
                this._indexUpload++;
                _indexUploadImage = 0;
                this.UploadOutletNokiaMerchandisingPotential();
                return;
            }

            if (merchandising.Qty.HasValue && merchandising.Qty > 0)
            {
                string image = string.Empty;

                string imageName = "Merchandising\\" + merchandising.Customerkey + "~" + merchandising.MerchandisingCode +
                                   "~" + _indexUploadImage.ToString() + ".jpeg";
                if (Utilities.ImageUtilities.CheckFileExist(imageName))
                {
                    image = Utilities.ImageUtilities.ConvertBitmapToString(imageName);
                }

                if (!string.IsNullOrEmpty(image))
                {
                    string formatRecDate = String.Format("{0:M/d/yyyy HH:mm:ss}", DateTime.Now);
                    this._proxy.UploadOutletNokiaMerchandisingPotentialAsync(GlobalInformation.SiteCode,
                        merchandising.Customerkey, merchandising.MerchandisingCode, image, formatRecDate,
                        _indexUploadImage.ToString());
                    _indexUploadImage++;
                    return;
                }
                else
                {
                    this._indexUploadImage++;
                    UploadOutletNokiaMerchandisingPotential();
                    return;
                }
            }
            else
            {
                this._indexUploadImage++;
                UploadOutletNokiaMerchandisingPotential();
            }
        }

        protected void ShowMessage(string message)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(message));
        }

        private void UpdateCustomers()
        {
            if (this._indexUpload < 0 || this.updateTcarcusts == null || this.updateTcarcusts.Count < 1 || this._indexUpload >= this.updateTcarcusts.Count)
            {
                this._indexUpload = 0;
                this.UpdateShopVisits();
                return;
            }

            TCARCUST customer = this.updateTcarcusts[this._indexUpload];

            this._proxy.InsertCustomerkeyAsync(customer.Customerkey,
                            GlobalInformation.SiteCode,
                           customer.Customername,
                           customer.ShopOwner,
                           customer.Address,
                           customer.Street,
                           customer.Ward,
                           customer.Town ?? string.Empty,
                           customer.Provice ?? string.Empty,
                           customer.DeliveryAddress ?? string.Empty,
                           customer.Phone ?? string.Empty,
                           customer.Week,
                           customer.TradeSegment ?? string.Empty,
                           customer.SubTradeSegment ?? string.Empty,
                           customer.Otype ?? string.Empty,
                           customer.VLevel ?? string.Empty,
                           customer.StatusType ?? string.Empty,
                           customer.Salespkey ?? string.Empty,
                           customer.Lat ?? string.Empty,
                           customer.Long ?? string.Empty,
                           customer.OutletTypeCode ?? string.Empty,
                           customer.GlobalTypeCode,
                           customer.GFKArea);
            //this._proxy.InsertCustomerkeyAsync(customer.Customerkey,
        }

        private void NewSaveCommand()
        {
            foreach (var customer in this._smartMobileContext.TCARCUST)
            {
                // Check mark of new customer
                if (customer.Customerkey.Contains("_") || customer.IsEdit == "2")
                {
                    updateTcarcusts.Add(customer);
                }
            }

            this._indexUpload = 0;
            this.UpdateCustomers();
        }

        private void UpdateShopVisits()
        {
            // this.BusyText = "Đồng bộ ghé thăm";
            if (this._indexUpload < 0 || this._smartMobileContext.Shopvisit.Any() || this._indexUpload >= this._smartMobileContext.Shopvisit.Count())
            {
                if (GlobalInformation.ArSaleSPType.Usertype == "SS")
                {
                    // TODO: Upload shop APPROVALCUSTOMERINFOR
                    string appro = string.Empty;
                    foreach (var approvalCus in this._smartMobileContext.APPROVALCUSTOMERINFOR.ToList())
                    {
                        appro += "@" + approvalCus.Customerkey + "#" + approvalCus.Type + "#" + approvalCus.Key + "#" +
                                 approvalCus.Values + "#" + approvalCus.Comment;
                    }

                    this._proxy.ApprovalCustomerInforAsync(GlobalInformation.SiteCode ?? string.Empty,
                        GlobalInformation.ArSaleSPType.Usercode ?? string.Empty, appro);
                }
                else
                {
                    this._indexUpload = 0;
                    this.UpdateImages();
                }

                return;
            }

            // Upload shop visit
            Shopvisit shopVisit = this._smartMobileContext.Shopvisit.ToList()[this._indexUpload];
            this._proxy.UploadShopvisitAsync(shopVisit.CustomerKey, shopVisit.Lat ?? string.Empty,
                    shopVisit.Long ?? string.Empty,
                    shopVisit.DateVisit ?? string.Empty, GlobalInformation.ArSaleSPType.Usercode ?? string.Empty,
                    shopVisit.StartTime ?? string.Empty,
                    shopVisit.EndTime ?? shopVisit.StartTime, GlobalInformation.SiteCode ?? string.Empty,
                    shopVisit.CMode ?? string.Empty);
        }

        private void UpdateImages()
        {
            var imageCustomerList = this._smartMobileContext.IMAGECUSTOMER.ToList();
            if (this._indexUpload < 0 || this._indexUpload >= imageCustomerList.Count || GlobalInformation.ReportImageTypes == null)
            {
                this._indexUpload = 0;
                this.UploadPhoneVendor();
                return;
            }

            var imageCustomer = imageCustomerList[this._indexUpload];
            string imagePath = imageCustomer.CustomerKey + "~" + imageCustomer.Type + ".Jpeg";
            if (Utilities.ImageUtilities.CheckFileExist(imagePath))
            {
                string image = Utilities.ImageUtilities.ConvertBitmapToString(imagePath);
                string formatRecDate = String.Format("{0:M/d/yyyy HH:mm:ss}",
                    DateTime.Parse(imageCustomer.Recdate));
                this._proxy.UploadCustomerImageAsync(
                    GlobalInformation.SiteCode,
                    imageCustomer.Salespkey,
                    imageCustomer.Type,
                    imageCustomer.CustomerKey,
                    image,
                    formatRecDate);
            }
            else
            {
                this._indexUpload++;
                this.UpdateImages();
            }
        }

        private void UpdateCurrentIn()
        {
            //this.BusyText = "Đồng bộ hình ảnh bên trong";
            var currentInDoorList = this._smartMobileContext.CurrentInDoorDoorDisplay.Where(c => c.Qty != null && c.Qty.Value > 0).OrderBy(c => c.Qty).ToList();

            if (this._indexUpload < 0 || this._indexUpload >= currentInDoorList.Count)
            {
                this._indexUpload = 0;
                _indexUploadImage = 0;

                // run next
                this.UpdateCurrentOut();
                return;
            }

            CurrentInDoorDoorDisplay currentIn = currentInDoorList[this._indexUpload];
            if (_indexUploadImage >= currentIn.QtyPicture)
            {
                this._indexUpload++;
                _indexUploadImage = 0;

                // run next
                this.UpdateCurrentIn();
                return;
            }

            if (currentIn.Qty.HasValue && currentIn.Qty > 0)
            {
                string image = string.Empty;

                string imageName = "NhapDuLieu\\" + "IN~" + currentIn.CustomerKey + "~" + currentIn.PhoneVendorCode + "~" + currentIn.InDoorTypeCode + "~" + _indexUploadImage.ToString() + ".jpeg";
                if (Utilities.ImageUtilities.CheckFileExist(imageName))
                {
                    image = Utilities.ImageUtilities.ConvertBitmapToString(imageName);
                }

                if (!string.IsNullOrEmpty(image))
                {
                    this._proxy.UploadCurrentInDoorDoorDisplayAsync(GlobalInformation.SiteCode,
                        currentIn.CustomerKey, currentIn.PhoneVendorCode,
                        currentIn.InDoorTypeCode, currentIn.Qty.ToString(), image, _indexUploadImage.ToString());
                    _indexUploadImage++;
                    return;
                }
                else
                {
                    this._indexUploadImage++;
                    this.UpdateCurrentIn();
                }
            }
            else
            {
                // move to next index of list
                this._indexUpload++;
                this.UpdateCurrentIn();
            }
        }

        private void UpdateCurrentOut()
        {
            //this.BusyText = "Đồng bộ hình ảnh bên ngoài";
            var currentOutDoorList = this._smartMobileContext.CurrentOutDoorDisplay.Where(c => c.Qty != null && c.Qty.Value > 0).OrderBy(c => c.Qty).ToList();
            if (this._indexUpload < 0 || this._indexUpload >= currentOutDoorList.Count)
            {
                this._indexUpload = 0;
                _indexUploadImage = 0;

                // run next
                this.UploadOutletNokiaMerchandisingPotential();
                return;
            }

            CurrentOutDoorDisplay currentOut = currentOutDoorList[this._indexUpload];
            if (_indexUploadImage >= currentOut.QtyPicture)
            {
                this._indexUpload++;
                _indexUploadImage = 0;

                // run next
                this.UpdateCurrentOut();
                return;
            }

            if (currentOut.Qty.HasValue && currentOut.Qty > 0)
            {
                string image = string.Empty;
                //for (int i = 0; i < currentOut.QtyPicture.Value; i++)
                //{
                string imageName = "NhapDuLieu\\" + "OUT~" + currentOut.Customerkey + "~" +
                                   currentOut.PhoneVendorCode + "~" +
                                   currentOut.OutDoorTypeCode + "~" + _indexUploadImage.ToString() + ".jpeg";
                if (Utilities.ImageUtilities.CheckFileExist(imageName))
                {
                    image = Utilities.ImageUtilities.ConvertBitmapToString(imageName);
                }

                // Update to table OutDoorPicture
                if (!string.IsNullOrEmpty(image))
                {
                    this._proxy.UploadCurrentOutDoorDisplayAsync(GlobalInformation.SiteCode,
                        currentOut.Customerkey, currentOut.PhoneVendorCode,
                        currentOut.OutDoorTypeCode, (currentOut.Qty ?? 0).ToString(), image, _indexUploadImage.ToString());
                    _indexUploadImage++;
                }
                else
                {
                    this._indexUploadImage++;
                    this.UpdateCurrentOut();
                }
            }
            else
            {
                // move to next index of list
                this._indexUpload++;
                this.UpdateCurrentOut();
            }
        }

        ////private void UpdateContactInfo()
        ////{
        ////    var outletContacts = this._smartMobileContext.OutletContact.ToList();
        ////    if (this._indexUpload < 0 || this._indexUpload >= outletContacts.Count)
        ////    {
        ////        this._indexUpload = 0;

        ////        // run next
        ////        UploadPhoneVendor();
        ////        return;
        ////    }

        ////    OutletContact outletContact = outletContacts[this._indexUpload];
        ////    this._proxy.UploadContactInforAsync(GlobalInformation.SiteCode,
        ////            outletContact.CustomerKey, outletContact.Fullname,
        ////            outletContact.Role, (outletContact.Gender ?? true).ToString(), outletContact.Email,
        ////            outletContact.Phone, outletContact.Title);
        ////}

        private void _proxy_UploadShopvisitCompleted(object sender, UploadShopvisitCompletedEventArgs e)
        {
            try
            {
                this._indexUpload++;
                this.UpdateShopVisits();
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(string.Format("Lỗi khi đồng bộ {0}\r\n{1}", "cửa hàng", ex.GetBaseException().ToString()));
            }
        }

        private void _proxy_ApprovalCustomerInforCompleted(object sender, ApprovalCustomerInforCompletedEventArgs e)
        {
            try
            {
                this._indexUpload++;
                this.UpdateImages();
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(string.Format("Lỗi khi đồng bộ {0}\r\n{1}", "duyệt khách hàng", ex.GetBaseException().ToString()));
            }
        }

        private void _proxy_UploadCurrentInDoorDoorDisplayCompleted(object sender, UploadCurrentInDoorDoorDisplayCompletedEventArgs e)
        {
            try
            {
                ////if (_indexUploadImage == 0)
                ////{
                ////    this._indexUpload++;
                ////    this.UpdateCurrentIn();
                ////}
                ////else
                ////{
                ////    _indexUploadImage++;
                this.UpdateCurrentIn();
                ////}
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(string.Format("Lỗi khi đồng bộ {0}\r\n{1}", "hình ảnh bên trong được các hãng hỗ trợ", ex.GetBaseException().ToString()));
            }
        }

        private void _proxy_UploadCurrentOutDoorDisplayCompleted(object sender, UploadCurrentOutDoorDisplayCompletedEventArgs e)
        {
            try
            {
                ////if (_indexUploadImage == 0)
                ////{
                ////    this._indexUpload++;
                ////    this.UpdateCurrentOut();
                ////}
                ////else
                ////{
                ////_indexUploadImage++;
                this.UpdateCurrentOut();
                ////}
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(string.Format("Lỗi khi đồng bộ {0}\r\n{1}", "hình ảnh bên ngoài được các hãng hỗ trợ", ex.GetBaseException().ToString()));
            }
        }

        ////private void _proxy_UploadContactInforCompleted(object sender, UploadContactInforCompletedEventArgs e)
        ////{
        ////    try
        ////    {
        ////        this._indexUpload++;
        ////        this.UpdateContactInfo();
        ////    }
        ////    catch (Exception ex)
        ////    {
        ////        this.ShowErrorMessage(string.Format("Lỗi khi đồng bộ {0}\r\n{1}", "thông tin liên lạc", ex.GetBaseException().ToString()));
        ////    }
        ////}

        private void ShowErrorMessage(string message)
        {
            // Finish
            this.IsBusy = false;
            this.ShowMessage(message);
            this.ThoatCommand.RaiseCanExecuteChanged(true);
            this.SaveCommand.RaiseCanExecuteChanged(true);
        }
    }
}
